<template>
    <div>
        <Row :gutter="10">
            <Col>
                <Card>
                    <Row class="live_wrapper clearfix">
                        <Button type="primary" style="float:right;width:90px;height: 34px;font-size: 14px;" @click="AddAd">添加</Button>
                        <Select v-model="filter.type" style="float:right; width: 200px;margin-right: 35px;" @on-change="search" placeholder="选择广告类型">
                          <Option value="0">全部</Option>
                          <Option value="1">轮播图</Option>
                          <Option value="2">视频</Option>
                          <Option value="3">图片</Option>
                      </Select>
                    </Row>
                    <Row class="margin-top-10 table_pattern table_pattern2">
                        <Table :loading="loading" :columns="columns" :data="list"></Table>
                    </Row>
                    <Row class="margin-top-10">
                        <Page :total="pagenation.totalPage" :page-size="pagenation.perPage"
                              :current="pagenation.currentPage" show-elevator show-total @on-change="change"></Page>
                    </Row>
                </Card>
            </Col>
        </Row>
        <Modal v-model="edit" :title="title" width="500px" :mask-closable="false" class="goods_modal" :z-index='100'>
            <Form :model="formValidate" ref="formValidate" :label-width="100">
                <FormItem label="广告类型" prop="type" class="view_type1">
                  <RadioGroup v-model="formValidate.type">
                    <Radio label="1">轮播图</Radio>
                    <Radio label="2">视频</Radio>
                    <Radio label="3">图片</Radio>
                  </RadioGroup>
                </FormItem>
                <FormItem label="封面" prop="cover">
                    <div>
                        <Row type="flex" justify="start" align="middle" class="height-100">
                            <div style="display: block;text-align: center;">
                                <Upload
                                        ref="upload"
                                        :max-size="1024"
                                        :show-upload-list="false"
                                        action="https://up.qiniup.com"
                                        :on-format-error="handleFormatError"
                                        :before-upload="handleBeforeUpload"
                                        :on-progress="handleProgress"
                                        :on-success="handleSuccess"
                                        :on-error="handleError"
                                        :data="{token:upload_token}"
                                >
                                    <Button cover="ios-cloud-upload-outline">上传文件</Button>
                                    <span style="padding-left:20px; color:#999">建议尺寸: 100*65px，JPG、PNG、JPEG格式，图片小于500KB</span>
                                </Upload>
                            </div>
                        </Row>
                        <Row class="margin-top-20">
                            <div class="" v-if="this.formValidate.cover">
                                <template>
                                    <div class="demo-upload-list">
                                        <img :src="this.formValidate.cover" style='width:150px; height:100px'>
                                        <div class="demo-upload-list-cover">
                                            <Icon type="ios-eye-outline" @click.native="handleView(this.formValidate.cover)"></Icon>
                                            <Icon type="ios-trash-outline" @click.native="handleRemove(1)"></Icon>
                                        </div>
                                    </div>
                                </template>
                            </div>
                        </Row>
                    </div>
                </FormItem>
                <FormItem label="视频" prop="cover" v-if='formValidate.type==2'>
                    <div>
                        <Row type="flex" justify="start" align="middle" class="height-100">
                            <div style="display: block;text-align: center;">
                                <Upload
                                        ref="upload"
                                        :max-size="512000"
                                        :show-upload-list="false"
                                        action="https://up.qiniup.com"
                                        :on-format-error="handleFormatError"
                                        :before-upload="handleBeforeUploadVideo"
                                        :on-progress="handleProgress"
                                        :on-success="handleVideoSuccess"
                                        :on-error="handleError"
                                        :data="{token:upload_token}"
                                >
                                    <Button cover="ios-cloud-upload-outline">上传视频</Button>
                                </Upload>
                            </div>
                        </Row>
                        <Row class="margin-top-20">
                            <div class="" v-if="this.formValidate.video_url">
                                <template>
                                    <div class="demo-upload-list">
                                        <img :src="this.video_cover" style='width:150px; height:100px'>
                                        <div class="demo-upload-list-cover">
                                            <Icon type="ios-eye-outline" @click.native="handleView(this.video_cover)"></Icon>
                                            <Icon type="ios-trash-outline" @click.native="handleRemove(2)"></Icon>
                                        </div>
                                    </div>
                                </template>
                            </div>
                        </Row>
                    </div>
                </FormItem>
                <FormItem label="跳转链接" prop="target" class="label_required">
                    <Input v-model="formValidate.target" placeholder="请输入跳转链接" style='width:60%'/>
                </FormItem>
                <FormItem label="广告位" prop="pid" v-if='0'>
                    <Select v-model="formValidate.pid" style="width:200px">
                        <Option v-for="(item, key) in ad_position_list" :value="item.id" :key="key">{{ item.name }}</Option>
                    </Select>
                </FormItem>
                <FormItem>
                    <Button :loading="saving" type="primary" @click="handleSubmit" style="width: 90px;height: 35px;border-radius: 0;font-size: 14px;">提交</Button>
                </FormItem>
            </Form>
        </Modal>
        <Modal v-model="visible" :title="title" width="500px" :mask-closable="false" class="goods_modal" :z-index='100'>
            <img :src="imgName">
        </Modal>
    </div>
</template>
<script>
    import config from '@/config'
    import { getQiniu, adList, editAd, changeAdStatus} from '@/api/main'
    export default {
        data() {
            return {
                upload_token: '',
                qiniu_url: '',
                visible: false,
                imgName: '',
                pagenation: {},
                columns: [
                    {
                        key: 'cover',
                        title: '封面',
                        align: 'center',
                        render: (h, params) => {
                            return h(
                                'div',
                                {
                                    style: {
                                        backgroundImage: 'url(' + params.row.cover + ')',
                                        width: '150px',
                                        height: '100px',
                                        objectFit:'cover',
                                        margin: '10px auto',
                                        position: 'relative',
                                        cursor: 'pointer',
                                        backgroundSize: 'cover',
                                    },
                                    on: {
                                        click: e => {
                                        },
                                    },
                                }
                            )
                        },
                    },
                    {
                        key: 'target',
                        title: '跳转链接',
                        align: 'center',
                        render: (h, params) => {
                            return h('strong', params.row.target)
                        },
                    },
                    {
                        key: 'type_name',
                        title: '广告类型',
                        align: 'center',
                        render: (h, params) => {
                            return h('strong', params.row.type_name)
                        },
                    },
                    {
                      key: 'status',
                      title: '状态',
                      width: 150,
                      align: 'center',
                      render: (h, params) => h('i-switch', {
                        props: {
                          value: params.row.status,
                          size: 'large',
                          'true-value': 1,
                          'false-value': 0
                        },
                        on: {
                          'on-change': () => {
                            this.changeAdStatus(params.row)
                          }
                        }
                      }, [
                        h('span', {
                          slot: 'open',
                          domProps: {
                            innerHTML: '开启'
                          }
                        }),
                        h('span', {
                          slot: 'close',
                          domProps: {
                            innerHTML: '关闭'
                          }
                        })
                      ]
                      )
                    },
                    {
                        key: 'created_time',
                        title: '创建时间',
                        align: 'center',
                        render: (h, params) => {
                            return h('strong', params.row.created_time)
                        },
                    },
                    {
                        title: '操作',
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                              h(
                                  'Button',
                                  {
                                      style: {
                                          marginRight: '5px',
                                          border:0,
                                          background:'transparent',
                                          fontSize:'14px',
                                          color:'#377EEF'
                                      },
                                      on: {
                                          click: () => {
                                            this.editAd(params.row)
                                          },
                                      },
                                  },
                                  '编辑',
                                ),
                                h(
                                    'Poptip',
                                    {
                                        props: {
                                            confirm: true,
                                            title: '您确定要删除该广告吗?',
                                            transfer: true,
                                        },
                                        on: {
                                            'on-ok': () => {
                                                let obj = {}
                                                obj.id = params.row.id
                                                obj.status = -1
                                                changeAdStatus(obj).then(res => {
                                                    if (res.code === 0) {
                                                        let _this = this
                                                        this.$Message.success('删除成功')
                                                        this.getAdList()
                                                    } else {
                                                        this.$Message.success(res.text)
                                                    }
                                                })
                                            },
                                        },
                                    },
                                    [
                                        h(
                                            'Button',
                                            {
                                                style: {
                                                    border:0,
                                                    background:'transparent',
                                                    fontSize:'14px',
                                                    color:'#377EEF'
                                                },
                                                props: {
                                                    placement: 'top',
                                                    size: 'small',
                                                },
                                            },
                                            '删除',
                                        ),
                                    ],
                                )
                            ])
                        },
                    },
                ],
                edit: false,
                title: '添加广告',
                list: [],
                loading: true,
                saving: false,
                video_cover: '',
                formValidate: {
                    id: 0,
                    pid: 0,
                    cover: '',
                    target: '',
                    type: '1',
                    video_url: '',
                },
                filter: {
                    page: 0,
                    type: '-1',
                },
            }
        },
        methods: {
            change: function(page) {
                this.loading = true
                this.filter.page = page-1
                this.getAdList()
            },
            search: function () {
                this.filter.page = 0
                this.ingetAdListit()
            },
            AddAd: function () {
              this.edit = true
              this.formValidate.id = 0
              this.title = '添加广告'
              this.handleReset('formValidate')
            },
            handleReset(name) {
                this.$refs[name].resetFields()
            },
            editAd: function(obj){
                this.formValidate = Object.assign({}, obj)
                this.formValidate.type = this.formValidate.type.toString()
                this.title = '编辑广告'
                this.edit = true
            },
            changeAdStatus(item) {
              let obj = {}
              obj.id = item.id
              obj.status = item.status == 0 ? 1 : 0
              changeAdStatus(obj).then(res => {
                  if (res.code === 0) {
                    this.$Message.success('操作成功')
                    this.getAdList()
                  } else {
                      this.$Message.error(res.text)
                  }
              })
            },
            handleSubmit() {
                if (this.formValidate.cover == '') {
                    this.$Message.error("请上传广告封面");return;
                }
                if (this.formValidate.type == 2 && this.formValidate.video_url == '') {
                    this.$Message.error("请上传广告视频");return;
                }
                editAd(this.formValidate).then(res => {
                    if (res.code === 0) {
                      this.$Message.success('操作成功')
                      this.edit = false
                      this.getAdList()
                    } else {
                        this.$Message.error(res.text)
                    }
                })
            },
            handleFormatError(file) {
                this.$Message.error('文件 ' + file.name + ' 格式不正确，请选择图片文件。')
            },
            handleBeforeUpload(file) {
                if(file.size > 1000*1024){
                    this.$Message.error("图片大小不能超过1M");
                    return;
                }
            },
            handleBeforeUploadVideo(file) {
                if(file.size > 512000000){
                    this.$Message.error("视频大小不能超过500M");
                    return;
                }
            },
            handleProgress(event, file) {},
            handleSuccess(event, file, fileList) {
                this.formValidate.cover = file.response.domain+file.response.key
            },
            handleVideoSuccess(event, file, fileList) {
                this.formValidate.video_url = file.response.domain+file.response.key
                this.video_cover = this.formValidate.video_url + '?vframe/jpg/offset/1'
            },
            handleError(event, file) {},
            handleView(img_url) {
                this.imgName = img_url
                this.visible = true
            },
            handleRemove(type) {
                if (type == 1) {
                    this.formValidate.cover = '';
                } else if (type == 2) {
                    this.video_cover = ''
                }
            },
            getAdList () {
                adList(this.filter).then(res => {
                    if (res.code == 0) {
                        this.list = res.data
                        this.loading = false
                        this.pagenation.currentPage = parseInt(res.currentPage) + 1
                        this.pagenation.totalPage = parseInt(res.totalPage)
                        this.pagenation.perPage = parseInt(res.perPage)
                    }
                })
            },
            async init() {
              let qiniu = await getQiniu()
              this.upload_token = qiniu.token
              this.qiniu_url = qiniu.url
            }
        },
        mounted() {
            this.init();
            this.getAdList()
        }
    }
</script>
